<template>
  <div>
    <a-spin :spinning="isLoading">
      <a-form :model="editForm" name="edit-form" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }" autocomplete="off"
        @finish="editPost">
        <a-form-item label="标题（中文）" name="title" :rules="[{ required: true, message: '请输入标题（中文）' }]">
          <a-input v-model:value="editForm.title" placeholder="请输入标题（中文）" />
        </a-form-item>
        <a-form-item label="标题（英文）" name="title_us" :rules="[{ required: true, message: '请输入标题（英文）' }]">
          <a-input v-model:value="editForm.title_us" placeholder="请输入标题（英文）" />
        </a-form-item>
        <a-form-item label="标题（繁体）" name="title_hk" :rules="[{ required: true, message: '请输入标题（繁体）' }]">
          <a-input v-model:value="editForm.title_hk" placeholder="请输入标题（繁体）" />
        </a-form-item>
        <a-form-item label="描述（中文）" name="desc" :rules="[{ required: true, message: '请输入描述（中文）' }]">
          <a-textarea v-model:value="editForm.desc" :rows="4" placeholder="请输入描述（中文）" />
        </a-form-item>
        <a-form-item label="描述（英文）" name="desc_us" :rules="[{ required: true, message: '请输入描述（英文）' }]">
          <a-textarea v-model:value="editForm.desc_us" :rows="4" placeholder="请输入描述（英文）" />
        </a-form-item>
        <a-form-item label="描述（繁体）" name="desc_hk" :rules="[{ required: true, message: '请输入描述（繁体）' }]">
          <a-textarea v-model:value="editForm.desc_hk" :rows="4" placeholder="请输入描述（繁体）" />
        </a-form-item>
        <a-form-item label="发布日期" name="add_date" :rules="[{ required: true, message: '请选择发布日期' }]">
          <a-date-picker v-model:value="editForm.add_date" value-format="YYYY-MM-DD" placeholder="请选择发布日期"
            style="width: 100%;" />
        </a-form-item>
        <a-form-item label="封面图" name="img" :rules="[{ required: true, message: '请上传封面图' }]">
          <a-upload v-model:value="editForm.img" name="img" list-type="picture-card" class="avatar-uploader"
            :show-upload-list="false" :action="`${uploadUrl}video`" @change="uploadFileChange" :accept="'image/*'"
            :headers="uploadAddHeaders">
            <img v-if="editForm.img" :src="imgDomainUrl + editForm.img" style="max-width: 100%;max-height: 100%;" />
            <div v-else>
              <loading-outlined v-if="isLoading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="视频地址" name="video" has-feedback help="可联系开发人员将视频上传到CDN，并提供视频地址填入此处"
          :rules="[{ required: true, message: '请输入视频地址' }]">
          <a-input v-model:value="editForm.video" placeholder="请输入视频地址" />
        </a-form-item>
        <a-form-item label="播放量" name="play_times_v" has-feedback
          :help="`显示给用户看的播放量 = 此处的值 + 真实播放量（真实播放量：${editFormExclude.play_times}）`"
          :rules="[{ required: true, message: '请输入播放量' }]">
          <a-input-number v-model:value="editForm.play_times_v" :min="0" :max="100000000000" placeholder="请输入播放量"
            style="width: 100%;" />
        </a-form-item>
        <a-form-item label="显示顺序" name="sort" has-feedback help="范围1~1000，越小显示越靠前"
          :rules="[{ required: true, message: '请输入显示顺序' }]">
          <a-input-number v-model:value="editForm.sort" :min="1" :max="1000" placeholder="请输入显示顺序"
            style="width: 100%;" />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-button type="primary" html-type="submit">立即提交</a-button>
          <a-button @click="editCancel" style="margin-left:10px;">取消</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue';
import { message } from 'ant-design-vue';
import { editVideo, getVideoDetail } from "@/api/admin";  //引入api
import { useRouter, useRoute } from 'vue-router';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';

const propsData = defineProps(['project_type', 'list_url']);

const { uploadUrl, uploadAddHeaders } = inject('uploadInfo');  // 依赖注入--文件、图片上传地址、请求头等
const { imgDomainUrl } = inject('imgDomainUrl');  // 依赖注入--文件、图片前的域名
const router = useRouter();
const route = useRoute();

const isLoading = ref(false);    // 控制loading

const editForm = ref({
  project_type: propsData.project_type,
  play_times_v: 0,
  sort: 1000,
});  // 编辑表单
const editFormExclude = ref({
  play_times: 0,
});  // 编辑表单（不能通过接口提交的字段）

const id = ref(route.query.id);  // 参数id
//根据参数id获取数据
const getUrlId = () => {
  const { checkURLParamsId } = inject('checkURLParamsId');  // 依赖注入--验证参数id正确性
  if (checkURLParamsId(id)) {
    isLoading.value = true;
    getVideoDetail({ id: id.value }).then((res) => {
      isLoading.value = false;
      if (res === false) return;

      editForm.value.id = res.data.id;
      editForm.value.img = res.data.img;
      editForm.value.video = res.data.video;
      editForm.value.title = res.data.title;
      editForm.value.title_us = res.data.title_us;
      editForm.value.title_hk = res.data.title_hk;
      editForm.value.desc = res.data.desc;
      editForm.value.desc_us = res.data.desc_us;
      editForm.value.desc_hk = res.data.desc_hk;
      editForm.value.play_times_v = res.data.play_times_v;
      editForm.value.project_type = res.data.project_type;
      editForm.value.sort = res.data.sort;
      editForm.value.status = res.data.status;
      editForm.value.add_date = res.data.add_date;

      editFormExclude.value.play_times = res.data.play_times;
    }).catch((rej) => {
      isLoading.value = false;
      message.error('获取数据失败：' + rej);
      editCancel();
    });
  }
}

// 获取接口数据列表
const editPost = () => {
  isLoading.value = true;

  if (editForm.value.img === undefined || editForm.value.img === null || editForm.value.img === '') {
    message.error('请上传图片');
    isLoading.value = false;
    return;
  }

  editVideo(editForm.value).then((res) => {
    if (res === false) return;

    message.success('操作成功，即将跳转……');
    setTimeout(() => { editCancel() }, 1000);
  }).catch((rej) => {
    isLoading.value = false;
    message.error('失败：' + rej);
  });
};

// 跳转到列表页
const editCancel = () => {
  isLoading.value = false;
  router.replace('/admin/video/' + propsData.list_url);
}

// 上传图片
const uploadFileChange = info => {
  if (info.file.status === 'uploading') {
    isLoading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    isLoading.value = false;
    if (info.file.response.code === 0) {
      editForm.value.img = info.file.response.data.down_path;
    } else {
      message.error(info.file.response.message);
    }
  }
  if (info.file.status === 'error') {
    isLoading.value = false;
    message.error('上传文件出错，请重新上传！');
  }
};

// 页面加载完成后，获取数据列表
onMounted(() => {
  getUrlId();
})
</script>

<style scoped></style>